package com.jy.appmarket.widget.essential;

import com.jy.appmarket.R;
import com.jy.appmarket.activity.PhoneEssentialActivity;
import com.jy.appmarket.statistics.event.widgetDisableEvent;
import com.jy.appmarket.statistics.event.widgetEnableEvent;
import com.jy.appmarket.statistics.umeng.myUmengStaticstics;
import com.jy.appmarket.utils.LogUtil;
import com.jy.appmarket.utils.Prefs;
import com.jy.appmarket.utils.WidgetProviderTools;
import com.rad.statistics.android.StatisticsAgent;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.RemoteViews;


public class PhoneEssentialWidgetProvider extends AppWidgetProvider{

	public final static String TAG = "PhoneEssentialWidgetProvider";

	private final static String NAME = "essential_widget_start_state";
	
	private final static String WIDGET_TYPE = "widget_PhoneEssential";
	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
		RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.appmarket_widget_layout);
		rv.setTextViewText(R.id.title, context.getString(R.string.app_requisite));
		rv.setImageViewResource(R.id.img,
				Prefs.hasEnterNecessariesWidget(context) ? R.drawable.ic_launcher_essential
						: R.drawable.ic_launcher_essential_new);

		int tag = String.valueOf(System.currentTimeMillis()).hashCode();
		Intent intent = new Intent(context, PhoneEssentialActivity.class);
		intent.putExtra(PhoneEssentialActivity.COME_FROM, PhoneEssentialActivity.FROM_WIDGET);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
		PendingIntent pi = PendingIntent.getActivity(context, tag, intent,
				PendingIntent.FLAG_UPDATE_CURRENT);
		rv.setOnClickPendingIntent(R.id.img, pi);

		appWidgetManager.updateAppWidget(appWidgetIds, rv);

	}

	// 第一个widget被创建时调用
	@Override
	public void onEnabled(Context context) {
		super.onEnabled(context);
		Log.d(TAG, "onEnabled");
		
		if (!WidgetProviderTools.isFirstStart(context, NAME, WidgetProviderTools.KEY)) {
			LogUtil.i(TAG, "essential first start");
			StatisticsAgent.onEvent(context, new widgetEnableEvent(WIDGET_TYPE));
			WidgetProviderTools.saveFirstStartedState(context, NAME, WidgetProviderTools.KEY);
		}
		myUmengStaticstics.onWidgetEnable(context, WIDGET_TYPE);
	}

	// 最后一个widget被删除时调用
	@Override
	public void onDisabled(Context context) {
		Log.d(TAG, "onDisabled");
		super.onDisabled(context);
		StatisticsAgent.onEvent(context, new widgetDisableEvent(WIDGET_TYPE));
		myUmengStaticstics.onWidgetDisable(context, WIDGET_TYPE);
	}
}